package com.zhugang.week01;

/**
 * @program algorithms
 * @description: oneEdit1
 * @author: chanzhugang
 * @create: 2022/04/06 23:35
 */
public class OneEdit1 {

    public static void main(String[] args) {
        OneEdit1 edit1 = new OneEdit1();
        String first = "pales";
        String second = "pal";
        boolean flag = edit1.oneEdit1(first, second);
        System.out.println(flag);
    }

    /**
     * 字符串有三种编辑：插入一个字符、删除一个字符或者替换一个字符。给定两个字符串，编写一个函数判断是否只需要一次（或零次）编辑
     */
    public boolean oneEdit1(String first, String second) {
        /**
         * 长度差大于1， false
         * 长度差相等， 要么完全相同，要么只有一个不同
         * 长度差等于1，插入或者删除
         */
        int m = first.length();
        int n = second.length();
        if (Math.abs(m - n) > 1) {
            return false;
        }

        int diffCount = 0;
        if (m == n) {
            for (int i = 0; i < m; i++) {
                if (first.charAt(i) != second.charAt(i)) {
                    diffCount++;
                }
            }
            return diffCount <= 1;
        }
        diffCount = 0;
        int i = 0, j = 0;
        while (i < m && j < n) {
            if (first.charAt(i) == second.charAt(j)) {
                i++;
                j++;
            } else {
                diffCount++;
                if (m > n) {
                    i++;
                } else {
                    j++;
                }
            }
        }
        return diffCount <= 1;
    }
}